package com.lujieni.springbootmybatis.aop;


import com.lujieni.springbootmybatis.context.DataPermissionContextHolder;
import com.lujieni.springbootmybatis.context.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 *
 *
 * @author 芋道源码
 */
@Aspect
@Slf4j
// 添加这个注解,让Spring管理这个Bean
@Component
public class DataPermissionAspect {

    /**
     * 方法级别Aop,方法入栈前被执行;joinPoint.proceed()会执行方法;方法出栈执行finally里的代码
     * DataPermissionContextHolder存的是一个List,所以可以标签里嵌套标签
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(com.lujieni.springbootmybatis.aop.DataPermission)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 获取注解
        DataPermission dataPermission = AnnotationUtils.findAnnotation(method, DataPermission.class);
        if (dataPermission != null) {
            log.info("DataPermissionAspect 拦截到方法: {}", method.getName());
            try {
                DataPermissionContextHolder.add(dataPermission);
                // 执行逻辑
                return joinPoint.proceed();
            } finally {
                DataPermissionContextHolder.remove();
            }
        } else {
            return joinPoint.proceed();
        }
    }

}
